<template>
  <div class="counter">
    <span class="counter-sub" @click="sub"> - </span>
    <span class="counter-num">{{number}}</span>
    <span class="counter-add" @click="add"> + </span>
  </div>
</template>

<script>
/*
扩展ares-ui的counter组件
 */
export default {
  name: 'ares-counter',
  props: {
    value: 0,
    min: '',
    max: '',
  },
  watch: {
    value(val) {
      this.number = val;
    },
  },
  data() {
    return {
      number: 0,
    };
  },
  created() {
    this.number = this.fixNumber(this.value);
    this.emissionChange();
  },
  methods: {
    // 修正数字，当前值范围在最小值和最大值之间
    fixNumber(curNumber = 0) {
      if (curNumber <= this.min) {
        return this.min;
      }
      if (this.min < this.max && curNumber >= this.max) {
        return this.max;
      }
      return curNumber;
    },
    add() {
      if ((this.max !== 0 && !this.max) || this.number < this.max) {
        this.number += 1;
      }
      this.number = this.fixNumber(this.number, 'add');
      this.emissionChange();
      this.$emit('addChange', this.number);
    },
    sub() {
      if ((this.min !== 0 && !this.min) || this.number > this.min) {
        this.number -= 1;
      }
      this.number = this.fixNumber(this.number);
      this.emissionChange();
      this.$emit('subChange', this.number);
    },
    emissionChange() {
      this.$emit('input', this.number);
      this.$emit('change', this.number);
    },
  },
};
</script>

<style lang="less" scoped>
.counter {
  &-sub {
    border-radius: 50%;
    border: 1px solid #E8EBEA;
    color: #313332;
    font-size: 18px;
    width: 20px;
    height: 20px;
    text-align: center;
    line-height: 20px;
    display: inline-block;
  }
  &-add {
    border-radius: 50%;
    border: 1px solid #E8EBEA;
    color: #313332;
    font-size: 18px;
    width: 20px;
    height: 20px;
    text-align: center;
    line-height: 20px;
    display: inline-block;
  }
  &-num {
    color: #313332;
    font-size: 18px
  }
}
</style>
